﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Web.UI;

namespace GoodStuff.Web.Controls
{
    /// <summary>
    /// Extensions for controls that inherit from System.Web.UI.Control (all ASP.Net server controls)
    /// </summary>
    public static class StateBagExtensions
    {
        /// <summary>
        /// Saves the value to the viewstate bases on the given key.
        /// </summary>
        /// <param name="viewState"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void SaveValue<T>(this StateBag viewState, string key, T value)
        {
            viewState[key] = value;
        }

        /// <summary>
        /// Retrieves the value of the given key from the viewstate.
        /// </summary>
        /// <param name="viewState"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T GetValue<T>(this StateBag viewState, string key)
        {
            return viewState.GetValue(key, default(T));
        }

        /// <summary>
        /// Retrieves the value of the given key from the viewstate, with a parameterised default value
        /// </summary>
        /// <param name="viewState"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T GetValue<T>(this StateBag viewState, string key, T defaultValue)
        {
            if (viewState[key] is T)
            {
                return (T)viewState[key];
            }
            return defaultValue;
        }
    }
}
